package master.photo.dao.impl;

import java.io.Serializable;
import java.util.List;

import master.photo.dao.GenericDAO;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class GenericDAOImpl extends HibernateDaoSupport implements GenericDAO {

	@Autowired
	public GenericDAOImpl(SessionFactory sessionFactory) {
		super();
		setSessionFactory(sessionFactory);
	}

	@Override
	public <T> T load(Class<T> clazz, Serializable id) {
		return getHibernateTemplate().load(clazz, id);
	}

	@Override
	public <T> List<T> findBy(Class<T> clazz, List<Criterion> criteria) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(clazz);
		if (CollectionUtils.isNotEmpty(criteria)) {
			for (Criterion c : criteria) {
				detachedCriteria.add(c);
			}
		}
		return getHibernateTemplate().findByCriteria(detachedCriteria);
	}

	@Override
	public <T> List<T> listByNativeSQL(Class clazz, String sql) {
		SQLQuery query = getHibernateTemplate().getSessionFactory()
				.getCurrentSession().createSQLQuery(sql).addEntity(clazz);
		return query.list();
	}

}
